import { RouteLocationNormalized, NavigationGuardNext } from 'vue-router'
import router from './router'
import useUserStore from './store/modules/user'
import pinia from './store'
import setting from './setting'

// 导航守卫

const userStore = useUserStore(pinia)


userStore.isLogin() && await userStore.updateMenuRoutes()
router.beforeEach(async (to: RouteLocationNormalized, _from: RouteLocationNormalized, next: NavigationGuardNext) => {
    console.log("🚀 ~ beforeEach router.getRoutes", to.path, router.getRoutes())
    document.title = `${setting.title} - ${to.meta.title}`
    if (userStore.isLogin()) {
        if (to.path === '/login') {
            next({ path: '/' });
        } else {
            if (!userStore.userInfo) {
                try {
                    await userStore.checkUserInfo();
                    // 退出登录后动态添加路由被自动清空了，这里重新执行一次
                    next({ path: to.redirectedFrom?.path || '/', replace: true })
                } catch (error) {
                    console.log("🚀 ~ router.beforeEach ~ error:", error)
                }
            } else {
                next()
            }
        }
    } else {
        if (to.path === '/login') {
            next();
        } else {
            next({ path: '/login', query: { redirect: to.fullPath } });
        }
    }
})

router.afterEach((_to: RouteLocationNormalized, _from: RouteLocationNormalized) => {

})